﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;

namespace Yule8xModel
{
    public class UserCaptchaModels
    {
        public static void AddCaptcha(int uid, string code, DateTime expire, string type)
        {
            string sqlstmt = string.Format("insert t_user_captcha ([code], [expire], user_id, [type]) values ('{0}', '{1}', {2}, '{3}');", code, expire.ToString("yyyy-MM-dd HH:mm:ss"), uid, type);
            DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteNonQuery(sqlstmt);
        }

        // 获取手机验证码接口
        public static string GetCaptchaCode(int uid, string type)
        {
            string sqlstmt = string.Format("select top 1 code from t_user_captcha where user_id={0} and [type]='{1}' and [expire] > '{2}' order by id desc", uid, type, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            LogUtil.Instance.WriteInfo("[获取手机验证码] " + sqlstmt);
            object value = DbFactory.Init(AppInfo.conn_yule8x_agent).GetValue(sqlstmt);
            return null == value ? string.Empty : value.ToString();
        }
        public static void ClearData()
        {
            string sqlstmt = string.Format("delete from t_user_captcha where [expire] < '{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteNonQuery(sqlstmt);
        }

        /// <summary>
        /// 判断验证码是否正确
        /// <para>有效时间5分钟</para>
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="type"></param>
        /// <param name="yzmcode"></param>
        /// <returns></returns>
        public static bool CheckCaptchaCode(int user_id, string type, string yzmcode)
        {
            if (string.IsNullOrEmpty(yzmcode))
            {
                return false;
            }
            string code = GetCaptchaCode(user_id, type);
            return RuntimeDataUtil.CheckSuperCaptcha(yzmcode) || yzmcode == code;
        }
    }
}